<template>
  <view class="chat-container" :style="chatContainerStyle">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="header-left">
        <picker
          :value="selectedGroupIndex"
          :range="groupNames"
          @change="handleGroupChange"
          class="group-picker"
        >
          <view class="picker-content">
            <text class="group-name">{{ currentGroupName }}</text>
            <text class="dropdown-icon">▼</text>
          </view>
        </picker>
      </view>

      <view class="header-center">
        <!-- 在线人数按钮 -->
        <view class="online-count-btn" @click="handleGroupAnnouncement">
          <text class="online-icon">👥</text>
          <text class="online-count">{{ currentGroupInfo.member_count || 0 }}</text>
        </view>
      </view>

      <view class="header-right">
        <view class="search-icon" @click="handleSearch">🔍</view>
        <view class="announcement-icon" @click="handleGroupAnnouncement">📢</view>
        <view class="avatar" @click="handleProfile">👤</view>
      </view>
    </view>

    <!-- 消息列表 -->
    <scroll-view
      class="message-list"
      scroll-y
      :scroll-top="scrollTop"
      :scroll-into-view="scrollIntoViewId"
      @scrolltoupper="loadMoreMessages"
    >
      <view
        v-for="message in messages"
        :key="message.id"
        class="message-item"
        :class="{ 'system-message': message.message_type === 'system' }"
        :id="'msg-' + message.id"
      >
        <!-- 系统消息 -->
        <view v-if="message.message_type === 'system'" class="system-content">
          <text class="system-text">{{ message.content }}</text>
        </view>

        <!-- 普通消息 -->
        <view
          v-else
          class="normal-message"
          :class="{ 'own-message': isCurrentUserMessage(message) }"
        >
          <!-- 头像 -->
          <view class="message-avatar">
            <view
              v-if="!isCurrentUserMessage(message)"
              class="avatar-container"
              @click="startPrivateChatWithUser(message.sender)"
            >
              <image
                v-if="message.sender && (message.sender.avatar || message.sender.avatar_url)"
                :src="message.sender.avatar || message.sender.avatar_url"
                class="avatar-image"
              />
              <view v-else class="avatar-placeholder">
                <text>{{ (message.sender && message.sender.nickname) ? message.sender.nickname.charAt(0) : '用' }}</text>
              </view>
            </view>

            <button
              v-else
              class="avatar-button"
              open-type="chooseAvatar"
              @chooseavatar="onChooseAvatar"
            >
              <image
                v-if="message.sender && (message.sender.avatar || message.sender.avatar_url)"
                :src="message.sender.avatar || message.sender.avatar_url"
                class="avatar-image"
              />
              <view v-else class="avatar-placeholder">
                <text>{{ (message.sender && message.sender.nickname) ? message.sender.nickname.charAt(0) : '用' }}</text>
              </view>
            </button>
          </view>

          <!-- 消息内容区域 -->
          <view class="message-content-area">
            <!-- 群组信息显示（仅在全国总群模式下显示） -->
            <view v-if="isAllGroupsMode && message.group && message.group.group_name" class="message-group-info">
              <text class="message-group-source">
                来自：{{ message.group.group_name }}
              </text>
            </view>

            <!-- 消息气泡 -->
            <view
              class="message-bubble"
              :class="{ 'own-bubble': isCurrentUserMessage(message) }"
              @longpress="showMessageMenu(message)"
            >
              <text class="message-text">{{ message.content }}</text>
            </view>

            <!-- 时间显示（移动到消息气泡下方） -->
            <view class="message-time-container">
              <text class="message-time">{{ formatTime(message.created_at) }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载更多提示 -->
      <view v-if="isLoadingMore" class="loading-more">
        <text>加载中...</text>
      </view>
    </scroll-view>

    <!-- 功能按钮区域 -->
    <view class="function-buttons">
      <button class="func-btn" style="background-color: #22c55e;" @click="handleCompanyTransfer">买卖公司</button>
      <button class="func-btn" style="background-color: #06b6d4;" @click="handleLocalPeers">本地同行</button>
      <button class="func-btn" style="background-color: #f59e0b;" @click="handleExposure">曝光台</button>
      <button class="func-btn" style="background-color: #8b5cf6;" @click="handleGroupAnnouncement">群公告</button>
    </view>

    <!-- 底部输入区域 -->
    <view class="input-section">
      <view class="input-container" @click="showExpandedInput">
        <input
          v-model="inputMessage"
          class="message-input"
          :placeholder="getInputPlaceholder()"
          @confirm="handleInputConfirm"
          confirm-type="send"
          :adjust-position="false"
          readonly
          disabled
        />
      </view>
      
      <!-- 私信按钮 -->
      <button class="private-msg-btn" @click="handlePrivateMessage">
        <text>私信</text>
        <view v-if="unreadPrivateMessageCount > 0" class="unread-badge">
          <text class="unread-count">{{ unreadPrivateMessageCount > 99 ? '99+' : unreadPrivateMessageCount }}</text>
        </view>
      </button>
    </view>

    <!-- 地区选择弹出框 -->
    <view v-if="showGroupSelector" class="modal-overlay" @click="hideGroupSelector">
      <view class="region-selector-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">选择发送群组</text>
          <text class="modal-close" @click="hideGroupSelector">×</text>
        </view>

        <view class="modal-content">
          <!-- 消息预览 -->
          <view class="message-preview">
            <text class="preview-label">消息内容：</text>
            <view class="preview-content">
              <text class="preview-text">{{ inputMessage }}</text>
            </view>
          </view>

          <view class="modal-quota-info">
            <text>{{ chatQuotaText }}</text>
          </view>

          <!-- 群组选择 -->
          <view class="group-selection">
            <view class="selection-header">
              <text class="selection-label">选择发送群组：</text>
              <picker
                class="default-group-picker"
                :range="groups"
                range-key="group_name"
                :value="defaultGroupPickerIndex"
                @change="handleDefaultGroupPickerChange"
              >
                <view class="default-picker-text">
                  默认：{{ defaultGroupName || '未设置' }}
                </view>
              </picker>
            </view>
            <view class="group-list">
              <view
                v-for="group in groups"
                :key="group.id"
                class="group-option"
                :class="{ selected: selectedGroupForSend && selectedGroupForSend.id === group.id }"
                @click="selectGroupForSend(group)"
              >
                <view class="group-option-content">
                  <text class="group-option-name">{{ group.group_name }}</text>
                  <view v-if="selectedGroupForSend && selectedGroupForSend.id === group.id" class="selected-icon">
                    <text>✓</text>
                  </view>
                </view>
              </view>
            </view>
          </view>

          <!-- 发送按钮 -->
          <view class="modal-footer">
            <button class="send-confirm-btn" @click="confirmSendToSelectedGroup" :disabled="!selectedGroupForSend">
              发送
            </button>
            <view class="cost-info">
              <text v-if="isChatFreeModeEnabled">本条消息将消耗1次免费额度</text>
              <text v-else>本条消息将消耗1个聊天额度</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 群公告弹出框 -->
    <view v-if="showAnnouncementModal" class="modal-overlay" @click="closeAnnouncementModal">
      <view class="announcement-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">群公告</text>
          <text class="modal-close" @click="closeAnnouncementModal">×</text>
        </view>

        <view class="modal-content">
          <!-- 群组信息 -->
          <view class="group-info-modal">
            <view class="group-avatar-small">
              <image
                v-if="currentGroupInfo.group_avatar"
                :src="currentGroupInfo.group_avatar"
                class="avatar-image-small"
              />
              <view v-else class="avatar-placeholder-small">
                <text>{{ currentGroupName.charAt(0) || '群' }}</text>
              </view>
            </view>
            <view class="group-details-modal">
              <text class="group-name-modal">{{ currentGroupName }}</text>
              <text class="member-count-modal">成员数量：{{ currentGroupInfo.member_count || 0 }}人</text>
            </view>
          </view>

          <!-- 公告内容 -->
          <view class="announcement-content-modal">
            <view v-if="currentGroupInfo.description && currentGroupInfo.description.trim()" class="announcement-text-modal">
              <text>{{ currentGroupInfo.description }}</text>
            </view>
            <view v-else class="no-announcement-modal">
              <text class="no-announcement-icon">📢</text>
              <text class="no-announcement-text">暂无群公告</text>
              <text class="no-announcement-desc">管理员还没有设置群公告</text>
            </view>
          </view>

          <!-- 更新时间 -->
          <view v-if="currentGroupInfo.created_at" class="update-time-modal">
            <text>更新时间：{{ formatTime(currentGroupInfo.created_at) }}</text>
          </view>
        </view>

        <!-- 加载状态 -->
        <view v-if="loadingAnnouncement" class="loading-modal">
          <text>加载中...</text>
        </view>
      </view>
    </view>

    <!-- 聊天套餐购买弹窗 -->
    <view v-if="showChatPackageModal" class="modal-overlay" @click="closeChatPackageModal">
      <view class="chat-package-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">购买聊天套餐</text>
          <text class="modal-close" @click="closeChatPackageModal">×</text>
        </view>

        <view class="modal-content">
          <view class="current-credits">
            <text class="credits-info">当前剩余：{{ userInfo?.chat_credits || 0 }}条消息</text>
          </view>

          <view class="packages-list">
            <view
              v-for="pkg in chatPackages"
              :key="pkg.id"
              class="package-item"
              :class="{ selected: selectedChatPackage && selectedChatPackage.id === pkg.id }"
              @click="selectChatPackage(pkg)"
            >
              <view class="package-header">
                <text class="package-title">{{ pkg.title }}</text>
                <view class="package-price">
                  <text class="price-value">{{ pkg.price }}</text>
                  <text class="price-unit">元</text>
                </view>
              </view>
              <view class="package-desc">{{ pkg.description }}</view>
              <view class="package-credits">{{ pkg.credits_amount }}条消息</view>

              <!-- 选中状态指示器 -->
              <view v-if="selectedChatPackage && selectedChatPackage.id === pkg.id" class="selected-indicator">
                <text class="check-icon">✓</text>
              </view>
            </view>
          </view>

          <view class="payment-info">
            <view class="total-amount">
              <text class="amount-label">支付金额：</text>
              <text class="amount-value">¥{{ selectedChatPackage?.price || 0 }}</text>
            </view>
            <button
              class="pay-btn"
              @click="handlePayChatPackage"
              :disabled="!selectedChatPackage || isPayingChatPackage"
            >
              {{ isPayingChatPackage ? '支付中...' : '立即支付' }}
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 输入框放大弹窗 -->
    <view 
      v-if="showExpandedModal" 
      class="expanded-input-modal"
      @click="hideExpandedInput"
    >
      <view class="expanded-modal-content" @click.stop>
        <!-- 弹窗头部 -->
        <view class="expanded-modal-header">
          <text class="expanded-modal-title">{{ getExpandedModalTitle() }}</text>
          <text class="expanded-modal-close" @click="hideExpandedInput">×</text>
        </view>

        <!-- 输入区域 -->
        <view class="expanded-input-area">
          <textarea 
            v-model="expandedInputMessage"
            class="expanded-textarea"
            :placeholder="getInputPlaceholder()"
            :maxlength="500"
            show-count
            auto-height
            :min-height="200"
            :adjust-position="false"
            :max-height="400"
            focus
          />
        </view>
        <view class="expanded-quota-info">
          <text>{{ chatQuotaText }}</text>
        </view>

        <!-- 全国总群模式下的群组选择 -->
        <view v-if="isAllGroupsMode" class="expanded-picker-row">
          <text class="expanded-group-label">选择发送群组：</text>
          <picker
            class="default-group-picker"
            :range="groups"
            range-key="group_name"
            :value="expandedGroupPickerIndex"
            @change="handleExpandedGroupPickerChange"
          >
            <view class="default-picker-text">
              当前：{{ selectedExpandedGroup?.group_name || defaultGroupName || '请选择群组' }}
            </view>
          </picker>
        </view>

        <!-- 弹窗底部按钮 -->
        <view class="expanded-modal-footer">
          <button class="expanded-cancel-btn" @click="hideExpandedInput">取消</button>
          <button 
            class="expanded-send-btn" 
            @click="handleExpandedSend"
            :disabled="!expandedInputMessage.trim() || (isAllGroupsMode && !selectedExpandedGroup)"
          >
            发送
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { chatAPI, userAPI, packageAPI, utils } from '@/utils/api.js'
import CreditChecker from '@/utils/creditChecker.js'
import NotificationUtils from '@/utils/notification.js'
import globalNotificationManager from '@/utils/globalNotificationManager.js'
import pageNotificationListener from '@/utils/pageNotificationListener.js'

const DEFAULT_GROUP_STORAGE_KEY = 'chat_default_group_id'
const FREE_USAGE_STORAGE_KEY = 'chat_free_usage'

const getTodayKey = () => new Date().toISOString().slice(0, 10)

const chatConfigState = ref({
  mode: 'paid',
  freeLimit: 0
})

const freeUsageCount = ref(0)
const defaultGroupId = ref(uni.getStorageSync(DEFAULT_GROUP_STORAGE_KEY) || null)

const loadFreeUsageFromStorage = () => {
  const today = getTodayKey()
  const record = uni.getStorageSync(FREE_USAGE_STORAGE_KEY)
  if (record && record.date === today) {
    freeUsageCount.value = Number(record.used) || 0
  } else {
    freeUsageCount.value = 0
    uni.setStorageSync(FREE_USAGE_STORAGE_KEY, { date: today, used: 0 })
  }
}

const incrementFreeUsage = (count = 1) => {
  loadFreeUsageFromStorage()
  freeUsageCount.value = Math.max(0, freeUsageCount.value + count)
  uni.setStorageSync(FREE_USAGE_STORAGE_KEY, {
    date: getTodayKey(),
    used: freeUsageCount.value
  })
}

const refreshChatConfig = async (force = false) => {
  const config = await CreditChecker.getChatConfig(force)
  chatConfigState.value = {
    mode: config.mode || 'paid',
    freeLimit: Number(config.freeLimit || 0)
  }
}

const defaultGroupName = computed(() => {
  const group = groups.value.find(item => item.id === defaultGroupId.value)
  return group ? group.group_name : ''
})

const defaultGroupPickerIndex = computed(() => {
  const idx = groups.value.findIndex(item => item.id === defaultGroupId.value)
  return idx === -1 ? 0 : idx
})

const expandedGroupPickerIndex = computed(() => {
  if (!selectedExpandedGroup.value) {
    return defaultGroupPickerIndex.value
  }
  const idx = groups.value.findIndex(item => item.id === selectedExpandedGroup.value.id)
  return idx === -1 ? 0 : idx
})

const chatQuotaText = computed(() => {
  if (chatConfigState.value.mode === 'free') {
    const limit = chatConfigState.value.freeLimit
    const remaining = Math.max(0, limit - freeUsageCount.value)
    if (limit <= 0) {
      return '免费模式暂不可用，请稍后再试'
    }
    return `今日剩余：${remaining}/${limit} 条免费消息`
  }
  const credits = Number(userInfo.value?.chat_credits || 0)
  return `套餐剩余：${credits} 条消息`
})

const isChatFreeModeEnabled = computed(() => chatConfigState.value.mode === 'free')

const handleDefaultGroupPickerChange = (event) => {
  const index = Number(event.detail?.value || 0)
  const group = groups.value[index]
  if (!group) return
  defaultGroupId.value = group.id
  uni.setStorageSync(DEFAULT_GROUP_STORAGE_KEY, group.id)
  selectedGroupForSend.value = group
  if (isAllGroupsMode.value) {
    selectedExpandedGroup.value = group
  }
  uni.showToast({
    title: `已设为默认：${group.group_name}`,
    icon: 'none',
    duration: 1500
  })
}

const handleExpandedGroupPickerChange = (event) => {
  const index = Number(event.detail?.value || 0)
  const group = groups.value[index]
  if (group) {
    selectedExpandedGroup.value = group
  }
}

const ensureDefaultGroupValid = () => {
  if (!defaultGroupId.value) return
  const exists = groups.value.some(group => group.id === defaultGroupId.value)
  if (!exists) {
    defaultGroupId.value = null
    uni.removeStorageSync(DEFAULT_GROUP_STORAGE_KEY)
  }
}

const pickDefaultGroup = () => {
  ensureDefaultGroupValid()
  if (!defaultGroupId.value && groups.value.length > 0) {
    defaultGroupId.value = groups.value[0].id
    uni.setStorageSync(DEFAULT_GROUP_STORAGE_KEY, defaultGroupId.value)
  }
  if (!selectedGroupForSend.value && defaultGroupId.value) {
    const group = groups.value.find(item => item.id === defaultGroupId.value)
    if (group) {
      selectedGroupForSend.value = group
    }
  }
}

const pickDefaultGroupForExpanded = () => {
  ensureDefaultGroupValid()
  if (!selectedExpandedGroup.value && defaultGroupId.value) {
    const group = groups.value.find(item => item.id === defaultGroupId.value)
    if (group) {
      selectedExpandedGroup.value = group
    }
  }
}

const getChatQuotaDataFromError = (error) => {
  return (
    error?.responseData?.data?.chat_quota ||
    error?.data?.chat_quota ||
    null
  )
}

const showFreeChatQuotaModal = (quotaData = {}) => {
  const remaining = Math.max(0, quotaData.remaining ?? 0)
  const dailyLimit = quotaData.dailyLimit ?? 0
  const required = quotaData.required ?? 1
  let content = ''

  if (remaining <= 0) {
    content = `今日免费消息次数已用完（每日上限 ${dailyLimit} 条）。`
  } else {
    content = `今日剩余 ${remaining} 条免费消息，本次操作需要 ${required} 条。`
  }

  content += '\n\n当前为免费模式，套餐额度不会生效，请等待次日自动恢复后再发送。'

  uni.showModal({
    title: '免费消息次数不足',
    content,
    showCancel: false,
    confirmText: '知道了'
  })
}

// 响应式数据
// 群组相关
const groups = ref([])
const selectedGroupIndex = ref(0)
const currentGroupId = ref('all') // 默认选择全国总群

// 消息相关
const messages = ref([])
const inputMessage = ref('')
const lastMessageId = ref(0)
const isLoadingMore = ref(false)
const scrollTop = ref(0)
const scrollIntoViewId = ref('')

// 轮询相关
const pollingTimer = ref(null)
const pollingInterval = ref(5000) // 5秒轮询一次
const groupRefreshTimer = ref(null)
const groupRefreshInterval = ref(60000) // 60秒刷新一次群组列表

// 用户信息
const userInfo = ref(null)
const isLoggedIn = ref(false)

// 群公告相关
const showAnnouncementModal = ref(false)
const currentGroupInfo = ref({})
const loadingAnnouncement = ref(false)

// 聊天套餐相关
const showChatPackageModal = ref(false)
const chatPackages = ref([])
const selectedChatPackage = ref(null)
const isPayingChatPackage = ref(false)

// 未读私信相关
const unreadPrivateMessageCount = ref(0)
const lastPrivateMessageCheckTime = ref(0)

// 地区选择相关
const showGroupSelector = ref(false)
const selectedGroupForSend = ref(null)

// 输入框放大弹窗相关
const showExpandedModal = ref(false)
const expandedInputMessage = ref('')
const selectedExpandedGroup = ref(null)

// 键盘高度相关
const keyboardHeight = ref(0)
const windowHeight = ref(0)
const pageHeight = ref(0)

// 计算属性
const groupNames = computed(() => {
  // 在群组列表顶部添加全国总群选项
  const allGroupsOption = '全国总群'
  const regularGroups = groups.value.map(group => group.group_name || '未知群组')
  return [allGroupsOption, ...regularGroups]
})

const currentGroupName = computed(() => {
  // 优先检查是否为全国总群模式
  if (selectedGroupIndex.value === 0 || currentGroupId.value === 'all') {
    console.log('计算群组名称: 全国总群模式', {
      selectedGroupIndex: selectedGroupIndex.value,
      currentGroupId: currentGroupId.value
    })
    return '全国总群'
  }
  // 获取具体群组名称
  const groupIndex = selectedGroupIndex.value - 1
  if (groupIndex >= 0 && groupIndex < groups.value.length) {
    const groupName = groups.value[groupIndex]?.group_name || '未知群组'
    console.log('计算群组名称: 具体群组', {
      selectedGroupIndex: selectedGroupIndex.value,
      groupIndex,
      groupName,
      groupsLength: groups.value.length
    })
    return groupName
  }
  console.log('计算群组名称: 索引超出范围', {
    selectedGroupIndex: selectedGroupIndex.value,
    groupIndex,
    groupsLength: groups.value.length
  })
  return '未知群组'
})

// 当前群组是否为全国总群
const isAllGroupsMode = computed(() => {
  return selectedGroupIndex.value === 0 || currentGroupId.value === 'all'
})

// 计算页面容器的动态样式 - 简化为固定高度
const chatContainerStyle = computed(() => {
  // 暂时使用固定100vh来排除高度计算问题
  return {
    height: '100vh'
  }
})


// 移除canSendMessage计算属性，保持原有的发送按钮样式

// 生命周期钩子
onMounted(() => {
  refreshChatConfig()
  loadFreeUsageFromStorage()
  initPage()
  
  // 检查审核结果通知
  checkAuditNotifications()

  // 获取系统信息并设置页面高度
  uni.getSystemInfo({
    success: (res) => {
      windowHeight.value = res.windowHeight
      pageHeight.value = res.windowHeight
      console.log('窗口高度:', res.windowHeight)
    }
  })

  // 监听键盘高度变化
  // #ifdef APP-PLUS
  uni.onKeyboardHeightChange((res) => {
    console.log('键盘高度变化:', res.height)
    keyboardHeight.value = res.height
  })
  // #endif
  
  // #ifdef MP-WEIXIN
  // 小程序平台监听键盘高度变化
  if (uni.onKeyboardHeightChange) {
    uni.onKeyboardHeightChange((res) => {
      console.log('小程序键盘高度变化:', res.height)
      keyboardHeight.value = res.height
    })
  }
  // #endif

  // 监听清除未读私信数量的事件
  uni.$on('clearUnreadPrivateMessages', () => {
    unreadPrivateMessageCount.value = 0
    // 更新最后查看私信的时间
    const currentTime = Date.now()
    uni.setStorageSync('lastPrivateMessageCheckTime', currentTime)
    lastPrivateMessageCheckTime.value = currentTime
  })
})

// 页面显示时刷新群组列表
onShow(() => {
  // 重新检查登录状态和用户信息，确保获取最新的额度数据
  checkLoginStatus()
  // 强制刷新用户信息，确保额度数据是最新的
  refreshUserInfo()
  // 刷新聊天配置和本地免费使用记录
  refreshChatConfig(true)
  loadFreeUsageFromStorage()
  // 刷新群组列表以获取最新的群名，保持当前选择
  loadGroups(true)
  
  // 检查审核结果通知
  checkAuditNotifications()
  
  // 通知页面监听器
  pageNotificationListener.onPageEnter('pages/chat/chat')
})

onUnmounted(() => {
  // 清除轮询定时器
  if (pollingTimer.value) {
    clearInterval(pollingTimer.value)
  }

  // 清除群组刷新定时器
  if (groupRefreshTimer.value) {
    clearInterval(groupRefreshTimer.value)
  }

  // 移除事件监听
  uni.$off('clearUnreadPrivateMessages')
})

// 方法定义
/**
 * 检查审核结果通知
 */
const checkAuditNotifications = async () => {
  try {
    // 使用全局管理器检查
    await globalNotificationManager.onPageShow('chat')
  } catch (error) {
    console.log('检查审核通知失败:', error)
  }
}

/**
 * 初始化页面
 */
const initPage = async () => {
  // 检查登录状态
  checkLoginStatus()

  // 加载群组列表
  await loadGroups()

  // 加载当前群组详细信息（包括成员数量）
  await loadCurrentGroupInfo()

  // 加载消息
  await loadMessages()

  // 如果已登录，加载未读私信数量
  if (isLoggedIn.value) {
    await pollUnreadPrivateMessages()
  }

  // 开始轮询
  startPolling()

  // 开始群组列表定时刷新
  startGroupRefresh()
}

/**
 * 检查登录状态
 */
const checkLoginStatus = () => {
  const token = uni.getStorageSync('token')
  const userInfoData = uni.getStorageSync('userInfo')
  const lastCheckTime = uni.getStorageSync('lastPrivateMessageCheckTime') || 0

  isLoggedIn.value = !!token
  userInfo.value = userInfoData
  lastPrivateMessageCheckTime.value = lastCheckTime
}

/**
 * 强制刷新用户信息
 */
const refreshUserInfo = async () => {
  if (!isLoggedIn.value) return
  
  try {
    const response = await userAPI.getCurrentUser()
    if (response.success) {
      userInfo.value = response.data
      uni.setStorageSync('userInfo', response.data)
      console.log('用户信息已刷新:', {
        chat_credits: response.data.chat_credits,
        publishing_credits: response.data.publishing_credits,
        contact_view_credits: response.data.contact_view_credits
      })
    }
  } catch (error) {
    console.error('刷新用户信息失败:', error)
  }
}

/**
 * 热门城市优先级配置
 * 数字越小优先级越高
 */
const CITY_PRIORITY = {
  // 江浙沪地区 - 最高优先级
  '上海': 1,
  '江苏': 1, 
  '浙江': 1,
  // 北京 - 第二优先级
  '北京': 2,
  // 广东地区 - 第三优先级
  '广东': 3,
  '深圳': 3,
  '广州': 3
}

/**
 * 获取城市优先级
 * @param {string} groupName 群组名称
 * @returns {number} 优先级数字，越小优先级越高，999为默认优先级
 */
const getCityPriority = (groupName) => {
  for (const [city, priority] of Object.entries(CITY_PRIORITY)) {
    if (groupName.includes(city)) {
      return priority
    }
  }
  return 999 // 默认优先级（最低）
}

/**
 * 按热门城市优先级排序群组
 * @param {Array} groupsList 群组列表
 * @returns {Array} 排序后的群组列表
 */
const sortGroupsByPriority = (groupsList) => {
  return groupsList.sort((a, b) => {
    const priorityA = getCityPriority(a.group_name)
    const priorityB = getCityPriority(b.group_name)
    
    // 如果优先级不同，按优先级排序
    if (priorityA !== priorityB) {
      return priorityA - priorityB
    }
    
    // 如果优先级相同，按群组名称排序保持稳定性
    return a.group_name.localeCompare(b.group_name, 'zh-CN')
  })
}

/**
 * 加载群组列表
 */
const loadGroups = async (keepCurrentSelection = false) => {
  try {
    // 保存当前选中的群组ID
    const currentSelectedGroupId = currentGroupId.value

    // 始终获取所有公开群组列表，让用户可以选择任何群组
    const result = await chatAPI.getGroups(1, 100) // 获取所有群组
    if (result.success && result.data.data.length > 0) {
      let groupsList = result.data.data.map(item => ({
        id: item.id,
        group_name: item.group_name
      }))
      
      // 按热门城市优先级排序
      groupsList = sortGroupsByPriority(groupsList)
      groups.value = groupsList
      ensureDefaultGroupValid()
      pickDefaultGroup()
      
      console.log('群组列表已按热门城市优先级排序:', {
        totalGroups: groupsList.length,
        firstFew: groupsList.slice(0, 5).map(g => g.group_name)
      })
    } else {
      // 如果API调用失败，使用默认群组（已按优先级排序）
      let defaultGroups = [
        { id: 1, group_name: '北京直辖市' },
        { id: 2, group_name: '上海直辖市' },
        { id: 3, group_name: '江苏省' },
        { id: 4, group_name: '浙江省' },
        { id: 5, group_name: '广东省' },
        { id: 6, group_name: '深圳同行群' },
        { id: 7, group_name: '广州同行群' }
      ]
      groups.value = sortGroupsByPriority(defaultGroups)
      ensureDefaultGroupValid()
      pickDefaultGroup()
    }

    if (keepCurrentSelection && currentSelectedGroupId) {
      // 如果需要保持当前选择，尝试找到对应的群组
      if (currentSelectedGroupId === 'all') {
        selectedGroupIndex.value = 0
        currentGroupId.value = 'all'
      } else {
        const groupIndex = groups.value.findIndex(group => group.id.toString() === currentSelectedGroupId.toString())
        if (groupIndex !== -1) {
          selectedGroupIndex.value = groupIndex + 1 // +1 因为全国总群在索引0
          currentGroupId.value = currentSelectedGroupId
        } else {
          // 如果找不到原来的群组，回退到全国总群
          selectedGroupIndex.value = 0
          currentGroupId.value = 'all'
        }
      }
    } else {
      // 默认选择全国总群（索引0）
      selectedGroupIndex.value = 0
      currentGroupId.value = 'all'
    }

    console.log('群组列表加载完成:', {
      selectedGroupIndex: selectedGroupIndex.value,
      currentGroupId: currentGroupId.value,
      groupsCount: groups.value.length,
      keepCurrentSelection
    })
  } catch (error) {
    console.error('加载群组失败:', error)
    // 出错时使用默认群组
    groups.value = [
      { id: 1, group_name: '默认群组' }
    ]
    ensureDefaultGroupValid()
    pickDefaultGroup()
    // 仍然默认选择全国总群
    selectedGroupIndex.value = 0
    currentGroupId.value = 'all'
    console.log('加载群组失败，回退到全国总群:', {
      selectedGroupIndex: selectedGroupIndex.value,
      currentGroupId: currentGroupId.value
    })
  }
}

/**
 * 加载当前群组详细信息
 */
const loadCurrentGroupInfo = async () => {
  try {
    if (currentGroupId.value === 'all') {
      // 全国总群模式，设置默认信息
      currentGroupInfo.value = {
        group_name: '全国总群',
        member_count: 0,
        description: '汇聚所有群组消息'
      }
    } else if (currentGroupId.value) {
      // 具体群组模式，获取群组详细信息
      const result = await chatAPI.getGroupDetail(currentGroupId.value)
      if (result.success) {
        currentGroupInfo.value = result.data
      }
    }
  } catch (error) {
    console.error('加载群组详细信息失败:', error)
    // 失败时设置默认值
    currentGroupInfo.value = {
      group_name: currentGroupName.value,
      member_count: 0,
      description: ''
    }
  }
}

/**
 * 加载消息列表
 */
const loadMessages = async () => {
  try {
    if (currentGroupId.value === 'all') {
      // 加载全国总群消息（所有群组的合并消息）
      const result = await chatAPI.getAllGroupsMessages(1, 50)
      if (result.success && result.data.data) {
        messages.value = result.data.data.reverse() // 反转数组，最新消息在底部
        if (messages.value.length > 0) {
          lastMessageId.value = Math.max(...messages.value.map(m => parseInt(m.id)))
        }
      }
    } else if (currentGroupId.value) {
      // 加载特定群组消息
      const result = await chatAPI.getGroupMessages(currentGroupId.value, 1, 50)
      if (result.success && result.data.data) {
        messages.value = result.data.data.reverse() // 反转数组，最新消息在底部
        if (messages.value.length > 0) {
          lastMessageId.value = Math.max(...messages.value.map(m => parseInt(m.id)))
        }
      }
    } else {
      // 无群组时清空消息
      messages.value = []
      lastMessageId.value = 0
    }

    // 滚动到底部
    nextTick(() => {
      scrollToBottom()
    })
  } catch (error) {
    console.error('加载消息失败:', error)
    utils.handleError(error, '加载消息失败')

    // 如果API调用失败，显示空消息列表
    messages.value = []
    lastMessageId.value = 0
  }
}

/**
 * 发送消息
 */
const sendMessage = async () => {
  if (!inputMessage.value.trim()) return

  if (!isLoggedIn.value) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    return
  }

  // 检查聊天消息额度
  const requiredCredits = currentGroupId.value === 'all' ? groups.value.length : 1
  const hasCredit = await CreditChecker.checkChatCredit(requiredCredits, {
    fromPage: '/pages/chat/chat'
  })
  if (!hasCredit) {
    return
  }

  const shouldConsumeCredits = await CreditChecker.shouldConsumeChatCredits()

  const messageContent = inputMessage.value.trim()

  // 检查消息是否包含手机号
  if (containsPhoneNumber(messageContent)) {
    uni.showModal({
      title: '消息包含敏感信息',
      content: '为保护用户隐私，不允许在群聊中发送手机号码。如需联系，请使用私聊功能。',
      showCancel: false,
      confirmText: '知道了'
    })
    return
  }

  inputMessage.value = ''

  try {
    let result
    if (currentGroupId.value === 'all') {
      // 全国总群模式：向所有群组发送消息
      result = await chatAPI.sendMessageToAllGroups(messageContent)

      if (result.success) {
        // // 显示发送成功提示
        // uni.showToast({
        //   title: result.message || `消息已发送到${result.data.broadcast_count}个群组`,
        //   icon: 'success',
        //   duration: 2000
        // })

        // 更新用户聊天额度信息（按群组数量扣除）
        const broadcastCount = result.data?.broadcast_count || requiredCredits || 1
        if (shouldConsumeCredits) {
          CreditChecker.reduceLocalCredit('chat', broadcastCount)
          if (userInfo.value) {
            userInfo.value.chat_credits = Math.max(0, (userInfo.value.chat_credits || 0) - broadcastCount)
          }
        } else {
          incrementFreeUsage(broadcastCount)
        }

        // 不需要手动添加到消息列表，轮询会自动获取新消息
      } else {
        throw new Error(result.message || '发送消息失败')
      }
    } else {
      // 具体群组模式：向单个群组发送消息
      result = await chatAPI.sendMessage(currentGroupId.value, messageContent)

      if (result.success) {
        // 添加到消息列表
        messages.value.push(result.data)
        lastMessageId.value = parseInt(result.data.id)

        // 更新用户信息中的聊天额度
        if (shouldConsumeCredits) {
          CreditChecker.reduceLocalCredit('chat', 1)
          if (userInfo.value) {
            userInfo.value.chat_credits = Math.max(0, (userInfo.value.chat_credits || 0) - 1)
          }
        } else {
          incrementFreeUsage(1)
        }

        // 滚动到底部
        nextTick(() => {
          scrollToBottom()
        })

        uni.showToast({
          title: '发送成功',
          icon: 'success'
        })
      } else {
        throw new Error(result.message || '发送失败')
      }
    }
  } catch (error) {
    console.error('发送消息失败:', error)

    const quotaData = getChatQuotaDataFromError(error)

    // 如果是禁言错误，显示禁言提示
    if (error.message && error.message.includes('禁言')) {
      uni.showModal({
        title: '发言受限',
        content: '您已被管理员禁言，无法发送消息。如有疑问，请联系管理员。',
        showCancel: false,
        confirmText: '知道了'
      })
    } else if (quotaData && quotaData.mode === 'free') {
      showFreeChatQuotaModal(quotaData)
    } else if (error.message && error.message.includes('额度不足')) {
      // 如果是额度不足错误，使用统一的额度检查工具处理
      const requiredCredits = currentGroupId.value === 'all' ? groups.value.length : 1
      await CreditChecker.checkChatCredit(requiredCredits, {
        fromPage: '/pages/chat/chat'
      })
    } else {
      utils.handleError(error, '发送消息失败')
    }

    // 恢复输入内容
    inputMessage.value = messageContent
  }
}

/**
 * 获取输入框提示文字
 */
const getInputPlaceholder = () => {
  if (isAllGroupsMode.value) {
    return '请点击输入你的消息'
  }
  return '请点击发送你的消息'
}

/**
 * 处理输入框确认事件
 */
const handleInputConfirm = () => {
  if (isAllGroupsMode.value) {
    // 全国总群模式下，回车键显示地区选择器
    showGroupSelectorModal()
  } else {
    // 普通群聊模式下，回车键直接发送消息
    sendMessage()
  }
}

/**
 * 显示群组选择器
 */
const showGroupSelectorModal = () => {
  if (!inputMessage.value.trim()) {
    uni.showToast({
      title: '请先输入消息内容',
      icon: 'none'
    })
    return
  }

  if (!isLoggedIn.value) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    return
  }

  pickDefaultGroup()
  if (!selectedGroupForSend.value && groups.value.length > 0) {
    selectedGroupForSend.value = groups.value[0]
  }

  showGroupSelector.value = true
}

/**
 * 隐藏群组选择器
 */
const hideGroupSelector = () => {
  showGroupSelector.value = false
  selectedGroupForSend.value = null
}

/**
 * 选择要发送的群组
 */
const selectGroupForSend = (group) => {
  selectedGroupForSend.value = group
}

/**
 * 确认发送到选中的群组
 */
const confirmSendToSelectedGroup = async () => {
  if (!selectedGroupForSend.value) {
    uni.showToast({
      title: '请选择一个群组',
      icon: 'none'
    })
    return
  }

  if (!inputMessage.value.trim()) {
    uni.showToast({
      title: '消息内容不能为空',
      icon: 'none'
    })
    return
  }

  // 检查聊天消息额度 (只需要1个额度)
  const hasCredit = await CreditChecker.checkChatCredit(1, {
    fromPage: '/pages/chat/chat'
  })
  if (!hasCredit) {
    return
  }

  const shouldConsumeCredits = await CreditChecker.shouldConsumeChatCredits()

  const messageContent = inputMessage.value.trim()

  // 检查消息是否包含手机号
  if (containsPhoneNumber(messageContent)) {
    uni.showModal({
      title: '消息包含敏感信息',
      content: '为保护用户隐私，不允许在群聊中发送手机号码。如需联系，请使用私聊功能。',
      showCancel: false,
      confirmText: '知道了'
    })
    return
  }

  try {
    // 发送消息到选中的群组
    const result = await chatAPI.sendMessageToSelectedGroup(
      messageContent, 
      selectedGroupForSend.value.id
    )

    if (result.success) {
      // 保存群组名称用于显示成功提示
      const groupName = selectedGroupForSend.value?.group_name || '选中的群组'
      
      // 清空输入框
      inputMessage.value = ''
      
      // 隐藏选择器
      hideGroupSelector()

      if (shouldConsumeCredits) {
        CreditChecker.reduceLocalCredit('chat', 1)
        if (userInfo.value) {
          userInfo.value.chat_credits = Math.max(0, (userInfo.value.chat_credits || 0) - 1)
        }
      } else {
        incrementFreeUsage(1)
      }

      uni.showToast({
        title: `消息已发送到${groupName}`,
        icon: 'success'
      })

      // 如果当前查看的不是全国总群，需要刷新消息列表
      if (currentGroupId.value !== 'all') {
        await loadMessages()
      }
    } else {
      throw new Error(result.message || '发送失败')
    }
  } catch (error) {
    console.error('发送消息到选中群组失败:', error)

    const quotaData = getChatQuotaDataFromError(error)

    // 处理错误
    if (error.message && error.message.includes('禁言')) {
      uni.showModal({
        title: '发言受限',
        content: '您已被管理员禁言，无法发送消息。如有疑问，请联系管理员。',
        showCancel: false,
        confirmText: '知道了'
      })
    } else if (quotaData && quotaData.mode === 'free') {
      showFreeChatQuotaModal(quotaData)
    } else if (error.message && error.message.includes('额度不足')) {
      await CreditChecker.checkChatCredit(1, {
        fromPage: '/pages/chat/chat'
      })
    } else {
      utils.handleError(error, '发送消息失败')
    }
  }
}

/**
 * 开始轮询新消息
 */
const startPolling = () => {
  if (pollingTimer.value) {
    clearInterval(pollingTimer.value)
  }

  pollingTimer.value = setInterval(() => {
    pollNewMessages()
  }, pollingInterval.value)
}

/**
 * 开始群组列表定时刷新
 */
const startGroupRefresh = () => {
  if (groupRefreshTimer.value) {
    clearInterval(groupRefreshTimer.value)
  }

  groupRefreshTimer.value = setInterval(() => {
    // 刷新群组列表，保持当前选择
    loadGroups(true)
  }, groupRefreshInterval.value)
}

/**
 * 轮询新消息
 */
const pollNewMessages = async () => {
  try {
    if (!currentGroupId.value) {
      return
    }

    let result
    if (currentGroupId.value === 'all') {
      // 轮询全国总群新消息
      result = await chatAPI.getAllGroupsNewMessages(lastMessageId.value)
    } else {
      // 轮询特定群组新消息
      result = await chatAPI.getNewMessages(currentGroupId.value, lastMessageId.value)
    }

    if (result.success && result.data.length > 0) {
      // 前端强化去重：基于消息ID和全国总群广播标识
      const existingMessageIds = new Set(messages.value.map(m => m.id))

      // 对于全国总群广播消息，还需要基于内容、发送者和时间进行去重
      const existingBroadcastMessages = new Set()
      messages.value.forEach(msg => {
        if (msg.broadcast_tag === 'national_broadcast') {
          const timeWindow = Math.floor(new Date(msg.created_at).getTime() / 5000) // 5秒时间窗口
          const key = `${msg.sender_id}_${msg.content}_${timeWindow}_${msg.broadcast_tag}`
          existingBroadcastMessages.add(key)
        }
      })

      const newMessages = result.data.filter(msg => {
        // 基于消息ID去重
        if (existingMessageIds.has(msg.id)) {
          return false
        }

        // 对于全国总群广播消息，基于内容、发送者和时间进行额外去重
        if (msg.broadcast_tag === 'national_broadcast') {
          const timeWindow = Math.floor(new Date(msg.created_at).getTime() / 5000) // 5秒时间窗口
          const key = `${msg.sender_id}_${msg.content}_${timeWindow}_${msg.broadcast_tag}`
          if (existingBroadcastMessages.has(key)) {
            return false
          }
          existingBroadcastMessages.add(key)
        }

        return true
      })

      if (newMessages.length > 0) {
        // 添加新消息到列表
        messages.value.push(...newMessages)

        // 更新最后消息ID
        const newLastId = Math.max(...result.data.map(m => parseInt(m.id)))
        if (newLastId > lastMessageId.value) {
          lastMessageId.value = newLastId
        }

        // 滚动到底部
        nextTick(() => {
          scrollToBottom()
        })
      }
    }

    // 同时轮询未读私信数量（仅在登录状态下）
    if (isLoggedIn.value) {
      await pollUnreadPrivateMessages()
    }
  } catch (error) {
    console.error('轮询新消息失败:', error)
    // 轮询失败不显示错误提示，避免频繁弹窗
  }
}

/**
 * 轮询未读私信数量
 */
const pollUnreadPrivateMessages = async () => {
  try {
    // 从本地存储获取最后查看私信的时间
    const lastCheckTime = uni.getStorageSync('lastPrivateMessageCheckTime') || 0
    const result = await chatAPI.getUnreadPrivateMessageCount(lastCheckTime)
    if (result.success) {
      unreadPrivateMessageCount.value = result.data.totalUnreadCount || 0
    }
  } catch (error) {
    console.error('轮询未读私信数量失败:', error)
    // 轮询失败不显示错误提示，避免频繁弹窗
  }
}

/**
 * 滚动到底部 - 增强延迟机制确保DOM完全渲染
 */
const scrollToBottom = () => {
  if (messages.value && messages.value.length > 0) {
    const last = messages.value[messages.value.length - 1]
    if (last && last.id) {
      // 使用多重nextTick确保DOM完全渲染
      nextTick(() => {
        nextTick(() => {
          nextTick(() => {
            // 先清空再赋值，确保scroll-view检测到变更
            scrollIntoViewId.value = ''
            nextTick(() => {
              scrollIntoViewId.value = `msg-${last.id}`
              // 额外的timeout保障机制，特别是对于全国总群的大量消息
              setTimeout(() => {
                scrollIntoViewId.value = `msg-${last.id}`
              }, 100)
            })
          })
        })
      })
    } else {
      nextTick(() => {
        nextTick(() => {
          // 缺少id时通过递增scrollTop兜底滚动
          scrollTop.value += 999999
        })
      })
    }
  }
}

/**
 * 格式化时间 - 今天显示时:分，之前显示年月日
 */
const formatTime = (timeStr) => {
  const time = new Date(timeStr)
  const now = new Date()

  // 判断是否为今天
  const isToday = time.getFullYear() === now.getFullYear() &&
                  time.getMonth() === now.getMonth() &&
                  time.getDate() === now.getDate()

  if (isToday) {
    // 今天的消息显示时:分
    const hours = time.getHours().toString().padStart(2, '0')
    const minutes = time.getMinutes().toString().padStart(2, '0')
    return `${hours}:${minutes}`
  } else {
    // 之前的消息显示年月日
    const year = time.getFullYear()
    const month = time.getMonth() + 1
    const day = time.getDate()
    return `${year}年${month}月${day}日`
  }
}

/**
 * 检查消息内容是否包含手机号
 */
const containsPhoneNumber = (content) => {
  if (!content) return false

  // 匹配手机号的正则表达式
  const phoneRegex = /1[3-9]\d{9}/g

  return phoneRegex.test(content)
}



// 事件处理方法
const handleGroupChange = async (e) => {
  const newIndex = parseInt(e.detail.value)
  selectedGroupIndex.value = newIndex

  console.log('群组切换:', { newIndex, groupsLength: groups.value.length })

  if (newIndex === 0) {
    // 选择全国总群
    currentGroupId.value = 'all'
    currentGroupInfo.value = {
      group_name: '全国总群',
      member_count: 0,
      description: '汇聚所有群组消息'
    }
    console.log('切换到全国总群')
  } else {
    // 选择具体群组
    const groupIndex = newIndex - 1
    if (groupIndex >= 0 && groupIndex < groups.value.length) {
      const selectedGroup = groups.value[groupIndex]
      currentGroupId.value = selectedGroup?.id
      console.log('切换到具体群组:', selectedGroup)
      // 加载新群组的详细信息
      await loadCurrentGroupInfo()
    } else {
      console.error('群组索引超出范围:', { groupIndex, groupsLength: groups.value.length })
      // 回退到全国总群
      selectedGroupIndex.value = 0
      currentGroupId.value = 'all'
      currentGroupInfo.value = {
        group_name: '全国总群',
        member_count: 0
      }
    }
  }

  // 重新加载消息
  loadMessages()
}

const handleSearch = () => {
  uni.showToast({ title: '搜索功能开发中', icon: 'none' })
}

const handleProfile = () => {
  if (isLoggedIn.value) {
    uni.navigateTo({ url: '/pages/user/profile' })
  } else {
    uni.navigateTo({ url: '/pages/login/login' })
  }
}

const handleCompanyTransfer = () => {
  uni.navigateTo({ url: '/pages/listings/list' })
}



const handleLocalPeers = () => {
  uni.navigateTo({ url: '/pages/local-services/index' })
}
const handleExposure = () => {
  uni.navigateTo({ url: '/pages/exposure/index' })
}



const handleGroupAnnouncement = async () => {
  // 跳转到群公告页面，传递群组ID（全国总群传递'all'）
  uni.navigateTo({
    url: `/pages/chat/group-info?groupId=${currentGroupId.value}`
  })
}

// 关闭群公告弹出框
const closeAnnouncementModal = () => {
  showAnnouncementModal.value = false
  // 不要清空 currentGroupInfo，因为顶部的在线人数按钮需要这些信息
}

const handlePrivateMessage = () => {
  if (!isLoggedIn.value) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    return
  }

  uni.navigateTo({
    url: '/pages/chat/private-list'
  })
}

// 与用户发起私聊
const startPrivateChatWithUser = async (sender) => {
  if (!sender || !sender.id) {
    uni.showToast({
      title: '用户信息不完整',
      icon: 'none'
    })
    return
  }

  // 检查是否是自己
  const currentUser = utils.getCurrentUser()
  if (currentUser && currentUser.id.toString() === sender.id.toString()) {
    uni.showToast({
      title: '不能与自己私聊',
      icon: 'none'
    })
    return
  }

  try {
    // 发起私聊
    const response = await chatAPI.startPrivateChat(sender.id)

    if (response.success) {
      // 跳转到私聊页面
      uni.navigateTo({
        url: `/pages/chat/private?userId=${sender.id}&nickname=${encodeURIComponent(sender.nickname || '用户')}`
      })
    } else {
      uni.showToast({
        title: response.message || '发起私聊失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('发起私聊错误:', error)
    uni.showToast({
      title: '发起私聊失败',
      icon: 'none'
    })
  }
}

const loadMoreMessages = () => {
  // 加载更多历史消息
  // uni.showToast({ title: '加载更多功能开发中', icon: 'none' })
}

/**
 * 判断是否为当前用户的消息
 */
const isCurrentUserMessage = (message) => {
  const currentUser = utils.getCurrentUser()
  if (!currentUser || !currentUser.id || !message || !message.sender || !message.sender.id) {
    return false
  }
  return currentUser.id.toString() === message.sender.id.toString()
}

/**
 * 显示消息菜单
 */
const showMessageMenu = (message) => {
  const menuItems = ['复制']

  // 如果是当前用户的消息，添加删除选项
  if (isCurrentUserMessage(message)) {
    menuItems.push('删除')
  } else {
    // 如果是其他用户的消息，添加私聊选项
    menuItems.push('私聊')
  }

  uni.showActionSheet({
    itemList: menuItems,
    success: (res) => {
      const selectedItem = menuItems[res.tapIndex]
      handleMessageAction(message, selectedItem)
    }
  })
}

/**
 * 处理消息操作
 */
const handleMessageAction = (message, action) => {
  switch (action) {
    case '复制':
      // 复制消息内容
      uni.setClipboardData({
        data: message.content,
        success: () => {
          uni.showToast({
            title: '已复制',
            icon: 'success'
          })
        }
      })
      break
    case '删除':
      // 删除消息（需要实现删除API）
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这条消息吗？',
        success: (res) => {
          if (res.confirm) {
            // TODO: 实现删除消息的API调用
            uni.showToast({
              title: '删除功能开发中',
              icon: 'none'
            })
          }
        }
      })
      break
    case '私聊':
      // 发起私聊
      startPrivateChatWithUser(message.sender)
      break
  }
}

/**
 * 处理用户选择头像
 */
const onChooseAvatar = async (e) => {
  try {
    const avatarUrl = e.detail.avatarUrl
    console.log('选择的头像临时路径:', avatarUrl)

    // 检查登录状态
    if (!isLoggedIn.value) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }

    // 显示上传中提示
    uni.showLoading({
      title: '上传头像中...'
    })

    try {
      // 上传头像到服务器
      const uploadResult = await userAPI.uploadAvatar(avatarUrl)

      if (uploadResult.success) {
        // 更新本地用户信息
        const currentUserInfo = uni.getStorageSync('userInfo') || {}
        currentUserInfo.avatar = uploadResult.data.url
        currentUserInfo.avatar_url = uploadResult.data.url
        uni.setStorageSync('userInfo', currentUserInfo)
        userInfo.value = currentUserInfo

        uni.hideLoading()
        uni.showToast({
          title: '头像上传成功',
          icon: 'success'
        })

        // 重新加载消息以显示新头像
        await loadMessages()
      } else {
        throw new Error(uploadResult.message || '上传失败')
      }
    } catch (uploadError) {
      uni.hideLoading()
      console.error('上传头像失败:', uploadError)
      uni.showToast({
        title: '上传头像失败',
        icon: 'none'
      })
    }

  } catch (error) {
    uni.hideLoading()
    console.error('选择头像失败:', error)
    uni.showToast({
      title: '选择头像失败',
      icon: 'none'
    })
  }
}

// 聊天套餐相关方法
/**
 * 处理购买聊天套餐
 */
const handleBuyChatCredits = async () => {
  if (!isLoggedIn.value) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    return
  }

  try {
    // 加载聊天套餐列表
    await loadChatPackages()
    showChatPackageModal.value = true
  } catch (error) {
    console.error('加载聊天套餐失败:', error)
    uni.showToast({
      title: '加载套餐失败',
      icon: 'none'
    })
  }
}

/**
 * 加载聊天套餐列表
 */
const loadChatPackages = async () => {
  try {
    const result = await packageAPI.getChatPackages()
    if (result.success) {
      chatPackages.value = result.data.items || []
      // 默认选择第一个套餐
      if (chatPackages.value.length > 0) {
        selectedChatPackage.value = chatPackages.value[0]
      }
    } else {
      throw new Error(result.message || '获取聊天套餐失败')
    }
  } catch (error) {
    console.error('加载聊天套餐失败:', error)
    throw error
  }
}

/**
 * 选择聊天套餐
 */
const selectChatPackage = (pkg) => {
  selectedChatPackage.value = pkg
}

/**
 * 支付聊天套餐
 */
const handlePayChatPackage = async () => {
  const pkg = selectedChatPackage.value
  if (!pkg) {
    uni.showToast({
      title: '请选择套餐',
      icon: 'none'
    })
    return
  }

  const packageId = pkg.id
  const purchasedCredits = Number(pkg.credits_amount || 0)

  try {
    isPayingChatPackage.value = true
    uni.showLoading({ title: '创建订单中...' })

    // 创建订单
    const orderResponse = await packageAPI.createOrder({
      package_id: packageId
    })

    if (!orderResponse.success) {
      uni.hideLoading()
      utils.handleError(new Error(orderResponse.message), '创建订单失败')
      return
    }

    const order = orderResponse.data.order
    const paymentParams = orderResponse.data.payment_params
    console.log('订单创建成功，订单号:', order.order_number)

    uni.hideLoading()

    // 调用微信支付
    if (paymentParams.mockMode) {
      // 模拟模式
      uni.showModal({
        title: '模拟支付',
        content: '当前为模拟支付模式，点击确定完成支付',
        success: async (res) => {
          if (res.confirm) {
            await checkChatPaymentStatus(order.order_number, purchasedCredits)
          } else {
            isPayingChatPackage.value = false
          }
        }
      })
    } else {
      // 真实支付模式
      try {
        await wx.requestPayment({
          timeStamp: paymentParams.timeStamp,
          nonceStr: paymentParams.nonceStr,
          package: paymentParams.package,
          signType: paymentParams.signType,
          paySign: paymentParams.paySign,
          success: async (res) => {
            console.log('微信支付成功:', res)
            await checkChatPaymentStatus(order.order_number, purchasedCredits)
          },
          fail: (err) => {
            console.error('微信支付失败:', err)
            isPayingChatPackage.value = false
            if (err.errMsg.includes('cancel')) {
              uni.showToast({
                title: '支付已取消',
                icon: 'none'
              })
            } else {
              uni.showToast({
                title: '支付失败',
                icon: 'none'
              })
            }
          }
        })
      } catch (error) {
        console.error('调用微信支付失败:', error)
        isPayingChatPackage.value = false
        uni.showToast({
          title: '支付调用失败',
          icon: 'none'
        })
      }
    }

  } catch (error) {
    uni.hideLoading()
    isPayingChatPackage.value = false
    utils.handleError(error, '支付失败')
    console.error('聊天套餐支付流程错误:', error)
  }
}

// 检查聊天套餐支付状态
const checkChatPaymentStatus = async (orderNumber, purchasedCredits, maxRetries = 10) => {
  let retries = 0

  const checkStatus = async () => {
    try {
      const statusResponse = await packageAPI.getPaymentStatus(orderNumber)

      if (statusResponse.success) {
        const paymentStatus = statusResponse.data.payment_status

        if (paymentStatus === 'paid') {
          uni.showToast({
            title: '支付成功',
            icon: 'success'
          })

          // 更新用户信息
          const updatedUserInfo = uni.getStorageSync('userInfo') || {}
          updatedUserInfo.chat_credits = (updatedUserInfo.chat_credits || 0) + purchasedCredits
          uni.setStorageSync('userInfo', updatedUserInfo)
          userInfo.value = updatedUserInfo

          // 关闭弹窗
          closeChatPackageModal()
          isPayingChatPackage.value = false

          console.log('聊天套餐购买成功，用户获得聊天消息次数:', purchasedCredits)
          return true
        } else if (paymentStatus === 'failed') {
          uni.showToast({
            title: '支付失败',
            icon: 'none'
          })
          isPayingChatPackage.value = false
          return true
        } else if (paymentStatus === 'pending' && retries < maxRetries) {
          // 继续轮询
          retries++
          setTimeout(checkStatus, 2000)
          return false
        } else {
          // 超时或其他状态
          uni.showToast({
            title: '支付状态确认超时',
            icon: 'none'
          })
          isPayingChatPackage.value = false
          return true
        }
      } else {
        throw new Error(statusResponse.message)
      }
    } catch (error) {
      console.error('查询支付状态失败:', error)
      if (retries < maxRetries) {
        retries++
        setTimeout(checkStatus, 2000)
      } else {
        uni.showToast({
          title: '支付状态查询失败',
          icon: 'none'
        })
        isPayingChatPackage.value = false
      }
    }
  }

  // 显示加载状态
  uni.showLoading({ title: '确认支付状态...' })

  const result = await checkStatus()
  if (result) {
    uni.hideLoading()
  }
}

/**
 * 关闭聊天套餐弹窗
 */
const closeChatPackageModal = () => {
  showChatPackageModal.value = false
  selectedChatPackage.value = null
  chatPackages.value = []
}

// 输入框放大弹窗相关方法
/**
 * 显示输入框放大弹窗
 */
const showExpandedInput = () => {
  if (!isLoggedIn.value) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    return
  }

  // 将原输入框内容同步到放大弹窗
  expandedInputMessage.value = inputMessage.value
  
  // 如果是全国总群模式，优先选中默认群组
  if (isAllGroupsMode.value) {
    selectedExpandedGroup.value = null
    pickDefaultGroupForExpanded()
  }
  
  showExpandedModal.value = true
}

/**
 * 隐藏输入框放大弹窗
 */
const hideExpandedInput = () => {
  showExpandedModal.value = false
  // 将弹窗内容同步回原输入框
  inputMessage.value = expandedInputMessage.value
  selectedExpandedGroup.value = null
}

/**
 * 获取放大弹窗标题
 */
const getExpandedModalTitle = () => {
  if (isAllGroupsMode.value) {
    return '发送消息到全国总群'
  }
  return `发送消息到${currentGroupName.value}`
}

/**
 * 选择放大弹窗中的群组
 */
/**
 * 处理放大弹窗中的发送
 */
const handleExpandedSend = async () => {
  if (!expandedInputMessage.value.trim()) {
    uni.showToast({
      title: '消息内容不能为空',
      icon: 'none'
    })
    return
  }

  // 同步消息内容到原输入框
  inputMessage.value = expandedInputMessage.value.trim()

  try {
    if (isAllGroupsMode.value) {
      // 全国总群模式：发送到选中的群组
      if (!selectedExpandedGroup.value) {
        uni.showToast({
          title: '请选择一个群组',
          icon: 'none'
        })
        return
      }

      // 检查聊天消息额度
      const hasCredit = await CreditChecker.checkChatCredit(1, {
        fromPage: '/pages/chat/chat'
      })
      if (!hasCredit) {
        return
      }

      const shouldConsumeCredits = await CreditChecker.shouldConsumeChatCredits()

      const messageContent = expandedInputMessage.value.trim()

      // 检查消息是否包含手机号
      if (containsPhoneNumber(messageContent)) {
        uni.showModal({
          title: '消息包含敏感信息',
          content: '为保护用户隐私，不允许在群聊中发送手机号码。如需联系，请使用私聊功能。',
          showCancel: false,
          confirmText: '知道了'
        })
        return
      }

      // 发送消息到选中的群组
      const result = await chatAPI.sendMessageToSelectedGroup(
        messageContent, 
        selectedExpandedGroup.value.id
      )

      if (result.success) {
        // 保存群组名称用于显示成功提示
        const groupName = selectedExpandedGroup.value?.group_name || '选中的群组'
        
        // 清空输入框
        inputMessage.value = ''
        expandedInputMessage.value = ''
        
        // 隐藏弹窗
        hideExpandedInput()

        if (shouldConsumeCredits) {
          CreditChecker.reduceLocalCredit('chat', 1)
          if (userInfo.value) {
            userInfo.value.chat_credits = Math.max(0, (userInfo.value.chat_credits || 0) - 1)
          }
        } else {
          incrementFreeUsage(1)
        }

        uni.showToast({
          title: `消息已发送到${groupName}`,
          icon: 'success'
        })

        // 如果当前查看的不是全国总群，需要刷新消息列表
        if (currentGroupId.value !== 'all') {
          await loadMessages()
        }
      } else {
        throw new Error(result.message || '发送失败')
      }
    } else {
      // 普通群聊模式：直接发送
      // 隐藏弹窗
      hideExpandedInput()
      // 调用原有发送方法
      await sendMessage()
    }
  } catch (error) {
    console.error('发送消息失败:', error)

    const quotaData = getChatQuotaDataFromError(error)

    // 处理错误
    if (error.message && error.message.includes('禁言')) {
      uni.showModal({
        title: '发言受限',
        content: '您已被管理员禁言，无法发送消息。如有疑问，请联系管理员。',
        showCancel: false,
        confirmText: '知道了'
      })
    } else if (quotaData && quotaData.mode === 'free') {
      showFreeChatQuotaModal(quotaData)
    } else if (error.message && error.message.includes('额度不足')) {
      const requiredCredits = isAllGroupsMode.value ? 1 : 1
      await CreditChecker.checkChatCredit(requiredCredits, {
        fromPage: '/pages/chat/chat'
      })
    } else {
      utils.handleError(error, '发送消息失败')
    }
  }
}
</script>

<style scoped>
.chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #ededed;
  box-sizing: border-box;
}

.header {
  background-color: #ffffff;
  padding: 20rpx 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid #e5e5e5;
  flex-shrink: 0;
  height: 100rpx; /* 合理的头部高度 */
  box-sizing: border-box;
}

.header-left {
  flex: 1;
}

.header-center {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1;
}

.group-picker {
  flex: 1;
}

.picker-content {
  display: flex;
  align-items: center;
  padding: 8rpx 0;
}

.group-name {
  font-size: 32rpx;
  font-weight: 500;
  margin-right: 8rpx;
  color: #000000;
}

.dropdown-icon {
  font-size: 20rpx;
  color: #666666;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 30rpx;
}

.online-count-btn {
  display: none; /* 隐藏在线人数按钮 */
}

.search-icon, .announcement-icon, .avatar {
  font-size: 36rpx;
  color: #666666;
  padding: 8rpx;
}

.search-icon:active, .announcement-icon:active, .avatar:active {
  opacity: 0.6;
}

.message-list {
  flex: 1;
  padding: 20rpx 30rpx;
  overflow-y: auto;
  background: #ededed;
  min-height: 0; /* 防止flex子元素过度拉伸 */
}

.message-item {
  margin-bottom: 20rpx;
}

.system-message {
  text-align: center;
}

.system-content {
  background: rgba(0, 0, 0, 0.1);
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
  display: inline-block;
  max-width: 400rpx;
}

.system-text {
  font-size: 24rpx;
  color: #999999;
  font-weight: 400;
}

.normal-message {
  display: flex;
  align-items: flex-start;
  gap: 20rpx;
  padding: 8rpx 0;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
}

.normal-message.own-message {
  flex-direction: row-reverse; /* 自己的消息头像在右边 */
  padding-right: 0; /* 确保没有额外的右边距 */
  justify-content: flex-start; /* 确保内容从左开始排列 */
}

	/* 群聊：为自己消息的右侧头像留出安全间距，避免被右边裁切 */
	.normal-message.own-message .message-avatar {
	  margin-right: 30rpx;
	}


.message-avatar {
  flex-shrink: 0;
  width: 80rpx;
  height: 80rpx;
}

.own-message .message-avatar {
  margin-right: 10rpx; /* 为自己的消息头像添加右边距 */
}

.avatar-button, .avatar-container {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
  border: none;
  background: transparent;
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
  box-sizing: border-box;
}

.avatar-button {
  outline: none;
  -webkit-appearance: none;
  appearance: none;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  background: #cccccc;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  color: #666666;
  font-weight: 600;
}

.avatar-image {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.message-content-area {
  flex: 1;
  min-width: 0;
}

.own-message .message-content-area {
  display: flex;
  flex-direction: column;
  align-items: flex-end; /* 自己的消息右对齐 */
}

.sender-info {
  display: none;
}

.sender-name {
  font-size: 26rpx;
  color: #666666;
  font-weight: 400;
}

/* 群组信息显示区域 */
.message-group-info {
  margin-bottom: 6rpx;
}

/* 时间显示容器（移动到消息气泡下方） */
.message-time-container {
  margin-top: 6rpx;
}

.message-time {
  font-size: 20rpx;
  color: #999999;
  text-align: left;
}

.own-message .message-time {
  text-align: right; /* 自己的消息时间右对齐 */
}

.message-group-source {
  font-size: 18rpx;
  color: #666666;
  text-align: left;
  background-color: #f5f5f5;
  padding: 2rpx 8rpx;
  border-radius: 8rpx;
  display: inline-block;
  max-width: fit-content;
  width: auto; /* 确保宽度自适应内容 */
}

.own-message .message-group-source {
  text-align: right;
  width: auto; /* 自己消息的标签也要自适应宽度 */
  max-width: 80%; /* 设置最大宽度避免过长 */
}

.own-message .message-group-info {
  display: flex;
  justify-content: flex-end;
  width: 100%; /* 确保容器占满宽度 */
}

.message-bubble {
  display: inline-block; /* 关键：自适应内容宽度 */
  background: #ffffff;
  border-radius: 8rpx;
  padding: 16rpx 20rpx;
  max-width: 80%; /* 与自己消息保持一致的上限 */
  word-wrap: break-word;
  position: relative;
  box-shadow: 0 1rpx 3rpx rgba(0, 0, 0, 0.1);
}

.message-bubble.own-bubble {
  background: #95ec69;
  color: #000000;
  max-width: 80%;
}

.message-bubble::before {
  display: none; /* 移除小三角 */
}

.message-text {
  font-size: 30rpx;
  line-height: 1.4;
  color: #000000;
  font-weight: 400;
}

.message-bubble.own-bubble .message-text {
  color: #000000;
}

.function-buttons {
  display: flex;
  padding: 10rpx 10rpx;
  gap: 8rpx;
  background-color: white;
  border-top: 1rpx solid #e5e5e5;
  flex-shrink: 0;
  height: 80rpx; /* 更紧凑的功能按钮区域高度 */
}

.func-btn {
  flex: 1;
  height: 60rpx;
  font-size: 24rpx; /* 适中的字体大小 */
  color: white;
  border: none;
  border-radius: 40rpx; /* 更圆润的按钮 */
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 500;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.input-section {
  background-color: white;
  padding: 20rpx;
  display: flex;
  align-items: center;
  gap: 20rpx;
  border-top: 1rpx solid #e5e5e5;
  flex-shrink: 0;
  box-sizing: border-box;
  height: 120rpx; /* 合理的输入区域高度 */
}

.region-select-btn {
  background: #07c160;
  color: white;
  border: none;
  border-radius: 6rpx;
  padding: 16rpx 24rpx;
  font-size: 28rpx;
  font-weight: 500;
}

.region-select-btn:disabled {
  background: #cccccc;
  color: #999999;
}

/* 地区选择弹出框样式 */
.region-selector-modal {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  width: 100%;
  max-height: 80vh;
  overflow: hidden;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  box-shadow: 0 -10rpx 30rpx rgba(0, 0, 0, 0.3);
  z-index: 1001;
}

/* 消息预览样式 */
.message-preview {
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background: #f8f8f8;
}

.preview-label {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 16rpx;
  display: block;
}

.preview-content {
  background: white;
  border-radius: 8rpx;
  padding: 20rpx;
  border: 1rpx solid #e5e5e5;
}

.preview-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.4;
}

/* 群组选择区域 */
.group-selection {
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.selection-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.selection-label {
  font-size: 28rpx;
  color: #333;
  font-weight: 600;
}

.default-group-picker {
  padding: 8rpx 20rpx;
  background: #f5f7fa;
  border-radius: 40rpx;
}

.default-picker-text {
  font-size: 24rpx;
  color: #606266;
}

.modal-quota-info {
  padding: 0 30rpx 20rpx;
  font-size: 24rpx;
  color: #909399;
}

.group-list {
  max-height: 300rpx;
  overflow-y: auto;
}

.group-option {
  background: #f8f8f8;
  border-radius: 12rpx;
  margin-bottom: 12rpx;
  padding: 20rpx;
  border: 2rpx solid transparent;
  transition: all 0.3s ease;
}

.group-option.selected {
  border-color: #07c160;
  background: #f0f9ff;
  box-shadow: 0 2rpx 8rpx rgba(7, 193, 96, 0.2);
}

.group-option-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.group-option-name {
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
  flex: 1;
}

.selected-icon {
  width: 36rpx;
  height: 36rpx;
  background: #07c160;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 22rpx;
  font-weight: bold;
}

/* 发送按钮区域 */
.modal-footer {
  padding: 30rpx;
  background: white;
}

.send-confirm-btn {
  width: 100%;
  background: #07c160;
  color: white;
  border: none;
  border-radius: 12rpx;
  padding: 24rpx;
  font-size: 32rpx;
  font-weight: 600;
  margin-bottom: 16rpx;
}

.send-confirm-btn:disabled {
  background: #cccccc;
  color: #999;
}

.cost-info {
  text-align: center;
}

.cost-info text {
  font-size: 24rpx;
  color: #666;
}

.input-container {
  flex: 1;
  display: flex;
  align-items: center;
  background: #f8f8f8;
  border-radius: 8rpx;
  padding: 0 20rpx;
  position: relative;
  min-height: 80rpx; /* 合理的容器最小高度 */
}

.input-container::before {
  content: '✏️';
  position: absolute;
  left: 15rpx;
  font-size: 28rpx;
  color: #999999;
}

.message-input {
  flex: 1;
  height: 80rpx; /* 合理的输入框高度 */
  font-size: 28rpx;
  border: none;
  background: transparent;
  padding-left: 60rpx;
}

/* 禁用状态下保持正常外观 */
.message-input[disabled] {
  opacity: 1;
  color: inherit;
  background: transparent;
}

.send-btn {
  background: #07c160;
  color: white;
  border: none;
  border-radius: 6rpx;
  padding: 16rpx 24rpx;
  font-size: 28rpx;
  font-weight: 500;
}

.send-btn:disabled {
  background: #cccccc;
  color: #999999;
}

.private-msg-btn {
  background: transparent;
  color: #666666;
  border: none;
  padding: 16rpx 24rpx;
  font-size: 28rpx;
  font-weight: 400;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.unread-badge {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  background-color: #ff4757;
  border-radius: 20rpx;
  min-width: 32rpx;
  height: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 8rpx;
  box-sizing: border-box;
}

.unread-count {
  color: white;
  font-size: 20rpx;
  font-weight: 600;
  line-height: 1;
}

.loading-more {
  text-align: center;
  padding: 20rpx;
  color: #999;
  font-size: 24rpx;
}

/* 群公告弹出框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding-top: 8vh;
  z-index: 1000;
}

.announcement-modal {
  background-color: #fff;
  border-radius: 20rpx;
  width: 90%;
  max-width: 600rpx;
  max-height: 80vh;
  overflow: hidden;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.3);
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background-color: #fafafa;
}

.modal-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
}

.modal-close {
  font-size: 48rpx;
  color: #999;
  line-height: 1;
  cursor: pointer;
}

.modal-content {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.group-info-modal {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.group-avatar-small {
  width: 80rpx;
  height: 80rpx;
  margin-right: 20rpx;
}

.avatar-image-small {
  width: 100%;
  height: 100%;
  border-radius: 12rpx;
}

.avatar-placeholder-small {
  width: 100%;
  height: 100%;
  background-color: #e5e5e5;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  color: #999;
  font-weight: 600;
}

.group-details-modal {
  flex: 1;
}

.group-name-modal {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.member-count-modal {
  font-size: 24rpx;
  color: #666;
}

.announcement-content-modal {
  margin-bottom: 20rpx;
}

.announcement-text-modal {
  font-size: 28rpx;
  line-height: 1.6;
  color: #333;
  white-space: pre-wrap;
  word-break: break-word;
}

.no-announcement-modal {
  text-align: center;
  padding: 60rpx 0;
}

.no-announcement-icon {
  font-size: 60rpx;
  display: block;
  margin-bottom: 15rpx;
}

.no-announcement-text {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 8rpx;
}

.no-announcement-desc {
  font-size: 24rpx;
  color: #999;
  display: block;
}

.update-time-modal {
  text-align: center;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
}

.update-time-modal text {
  font-size: 24rpx;
  color: #999;
}

.loading-modal {
  text-align: center;
  padding: 40rpx 0;
  color: #666;
  font-size: 28rpx;
}

/* 聊天次数显示样式 */
.credits-display {
  font-size: 20rpx;
  color: #999999;
  margin-right: 10rpx;
  white-space: nowrap;
}

/* 聊天套餐弹窗样式 */
.chat-package-modal {
  background-color: #fff;
  border-radius: 20rpx;
  width: 90%;
  max-width: 600rpx;
  max-height: 80vh;
  overflow: hidden;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.3);
}

.current-credits {
  text-align: center;
  padding: 20rpx;
  background-color: #f8f8f8;
  border-bottom: 1rpx solid #e5e5e5;
}

.credits-info {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.packages-list {
  max-height: 400rpx;
  overflow-y: auto;
  padding: 20rpx;
}

.package-item {
  border: 2rpx solid #e5e5e5;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 16rpx;
  position: relative;
  background-color: #fff;
  transition: all 0.3s ease;
}

.package-item.selected {
  border-color: #07c160;
  background-color: #f0f9ff;
}

.package-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8rpx;
}

.package-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.package-price {
  display: flex;
  align-items: baseline;
}

.price-value {
  font-size: 36rpx;
  font-weight: 700;
  color: #ff6b35;
}

.price-unit {
  font-size: 24rpx;
  color: #ff6b35;
  margin-left: 4rpx;
}

.package-desc {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.package-credits {
  font-size: 28rpx;
  color: #07c160;
  font-weight: 500;
}

.selected-indicator {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: #07c160;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.check-icon {
  color: white;
  font-size: 24rpx;
  font-weight: bold;
}

.payment-info {
  padding: 20rpx;
  border-top: 1rpx solid #e5e5e5;
  background-color: #fafafa;
}

.total-amount {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.amount-label {
  font-size: 28rpx;
  color: #333;
}

.amount-value {
  font-size: 36rpx;
  font-weight: 700;
  color: #ff6b35;
}

.pay-btn {
  width: 100%;
  background: #07c160;
  color: white;
  border: none;
  border-radius: 8rpx;
  padding: 24rpx;
  font-size: 32rpx;
  font-weight: 600;
}

.pay-btn:disabled {
  background: #cccccc;
  color: #999999;
}

/* 输入框放大弹窗样式 */
.expanded-input-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding-top: 12vh; /* 固定在屏幕上方12%的位置 */
  z-index: 1500;
}

.expanded-modal-content {
  background-color: #fff;
  border-radius: 20rpx;
  width: 95%;
  max-width: 700rpx;
  max-height: 85vh;
  overflow: hidden;
  box-shadow: 0 20rpx 40rpx rgba(0, 0, 0, 0.3);
  display: flex;
  flex-direction: column;
}

.expanded-modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background-color: #fafafa;
  flex-shrink: 0;
}

.expanded-modal-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
}

.expanded-modal-close {
  font-size: 48rpx;
  color: #999;
  line-height: 1;
  cursor: pointer;
  padding: 10rpx;
}

.expanded-input-area {
  padding: 30rpx;
  flex: 1;
  min-height: 200rpx;
}

.expanded-textarea {
  width: 100%;
  min-height: 200rpx;
  max-height: 400rpx;
  font-size: 32rpx;
  line-height: 1.5;
  color: #333;
  background-color: #f8f8f8;
  border: 1rpx solid #e5e5e5;
  border-radius: 12rpx;
  padding: 20rpx;
  box-sizing: border-box;
  resize: none;
}

.expanded-textarea:focus {
  border-color: #07c160;
  background-color: #fff;
}

.expanded-quota-info {
  padding: 0 30rpx 10rpx;
  font-size: 24rpx;
  color: #909399;
}

.expanded-picker-row {
  padding: 0 30rpx 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 20rpx;
}

.expanded-group-label {
  font-size: 28rpx;
  color: #333;
  font-weight: 600;
}

.expanded-picker-row .default-group-picker {
  padding: 8rpx 20rpx;
  background: #f5f7fa;
  border-radius: 40rpx;
}

.expanded-modal-footer {
  padding: 30rpx;
  background-color: #fff;
  border-top: 1rpx solid #f0f0f0;
  display: flex;
  gap: 20rpx;
  flex-shrink: 0;
}

.expanded-cancel-btn {
  flex: 1;
  height: 80rpx;
  background: #f8f8f8;
  color: #666;
  border: 1rpx solid #e5e5e5;
  border-radius: 12rpx;
  font-size: 30rpx;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
}

.expanded-cancel-btn:active {
  background-color: #e5e5e5;
}

.expanded-send-btn {
  flex: 2;
  height: 80rpx;
  background: #07c160;
  color: white;
  border: none;
  border-radius: 12rpx;
  font-size: 32rpx;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
}

.expanded-send-btn:disabled {
  background: #cccccc;
  color: #999;
}

.expanded-send-btn:active:not(:disabled) {
  background-color: #06a850;
}
</style>
